/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.common.web.JsonAction
   Module Description   :

   Date Created      : 2010/3/3
   Original Author   : jeff.ma
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.common.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.xwork.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;
import com.yaodian100.core.admin.service.UserService;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.entity.SimplePager;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.core.menu.service.MenuService;
import com.yaodian100.ec.category.service.CategoryService;
import com.yaodian100.ec.coupon.service.CouponService;
import com.yaodian100.ec.delivery.service.DeliveryRuleService;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.product.service.ProductService;
import com.yaodian100.ec.search.SearchManager;
import com.yaodian100.ec.shelf.service.ShelfService;
import com.yaodian100.ec.shopping.service.CartOrdersService;
import com.yaodian100.ec.supplierapply.service.SupplierApplyService;

/**
 * @author jeff.ma
 * 
 */
public class JsonAction extends ActionSupport {

	/** serialVersionUID */
	private static final long serialVersionUID = 7227951275641661337L;
	private final Logger logger = LoggerFactory.getLogger(JsonAction.class);
	private String id;
	private String couponCode;
	private Map<String, String> paramMap;
	private List objList;
	private Object obj;
	private Map jsonOut;
	private List<Map<String, Object>> couponLogsList;
	private String cartId;
	private final SimplePager pager = new SimplePager(0, 10);

	@Autowired
	private ProductService productService;
	@Autowired
	private CouponService couponService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private UserService userService;
	@Autowired
	private ShelfService shelfService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private SupplierApplyService supplierApplyService;
	@Autowired
	private MenuService menuService;
	@Resource
	private SearchManager searchManager;
	@Resource
	private BaseManager baseMgr;
	private Menu domainSrc;
	@Autowired
	private DeliveryRuleService deliveryRuleService;
	@Autowired
	private CartOrdersService cartordersService;

	public Menu getDomainSrc() {
		return domainSrc;
	}

	public void setDomainSrc(Menu domainSrc) {
		this.domainSrc = domainSrc;
	}

	/**
	 * @return the id
	 */
	public String getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(String id) {
		this.id = id;
	}

	/**
	 * @return the objList
	 */
	public List getObjList() {
		return objList;
	}

	/**
	 * @return the obj
	 */
	public Object getObj() {
		return obj;
	}

	/**
	 * @return the paramMap
	 */
	public Map<String, String> getParamMap() {
		if (paramMap == null) {
			paramMap = new HashMap();
		}
		return paramMap;
	}

	/**
	 * @param paramMap the paramMap to set
	 */
	public void setParamMap(Map<String, String> paramMap) {
		this.paramMap = paramMap;
	}

	/**
	 * @return the jsonOut
	 */
	public Map getJsonOut() {
		return jsonOut;
	}

	/**
	 * @return the pager
	 */
	public SimplePager getPager() {
		return pager;
	}

	public int getPage() {
		return pager.getCurrentPage();
	}

	public void setPage(int page) {
		pager.setCurrentPage(page);
	}

	/** default constructor */
	public JsonAction() {
	}

	/**
	 * paramMap['loginId'] paramMap['name'] paramMap['email'] paramMap['mobile']
	 * 
	 * @return
	 */
	public String memberList() {
		logger.debug("param:{}", getParamMap());
		CommonCriteria cri = new CommonCriteria();
		if (StringUtils.isNotBlank(getParamMap().get("loginId"))) {
			cri.addEq("loginId", getParamMap().get("loginId"));
		}
		if (StringUtils.isNotBlank(getParamMap().get("memberId"))) {
			cri.addEq("memberId", getParamMap().get("memberId"));
		}
		if (StringUtils.isNotBlank(getParamMap().get("name"))) {
			cri.addRlike("name", getParamMap().get("name"));
		}
		if (StringUtils.isNotBlank(getParamMap().get("email"))) {
			cri.addRlike("email", getParamMap().get("email"));
		}
		if (StringUtils.isNotBlank(getParamMap().get("mobile"))) {
			cri.addRlike("mobile", getParamMap().get("mobile"));
		}
		pager.setTotalSize(memberService.getListSize(cri).longValue());
		objList = memberService.getList(pager.getCurrentPage() * pager.getPageRecord(), pager.getPageRecord(), cri,
				new String[] { "loginId asc" });
		Menu domainSrc = menuService.get("Site.domain");

		List<Member> objListOut = new ArrayList<Member>();

		for (Object obj : objList) {
			Member member = (Member) obj;
			String domainSrcStr = " ";
			if (domainSrc.getOptions().containsKey(member.getDomainSrc())) {
				domainSrcStr = domainSrc.getOptions().get(member.getDomainSrc()).getName();
			}
			member.setDomainSrc(domainSrcStr);
			objListOut.add(member);

		}

		jsonOut = new HashMap();
		jsonOut.put("total", pager.getPageSize());
		jsonOut.put("page", pager.getCurrentPage());
		jsonOut.put("records", pager.getTotalSize());
		jsonOut.put("objList", objListOut);
		return "jsonListOut";
	}

	public String memberPops() {
		return "memberPops";
	}

	public String couponLogs() {
		return "couponLogs";
	}

	public String couponLogList() {
		if (StringUtils.isNotBlank(couponCode)) {
			couponLogsList = couponService.getItemLogs(couponCode);
		}
		jsonOut = new HashMap();
		jsonOut.put("couponLogsList", couponLogsList);
		return "jsonListOut";
	}

	public String supplierList() {
		// logger.debug("param:{}", getParamMap());
		CommonCriteria cri = new CommonCriteria();
		if (StringUtils.isNotBlank(getParamMap().get("supplierID"))) {
			cri.addRlike("supplierID", getParamMap().get("supplierID"));
		}
		if (StringUtils.isNotBlank(getParamMap().get("companyName"))) {
			cri.addRlike("companyName", getParamMap().get("companyName"));
		}
		cri.addEq("status", 1);
		cri.addNe("approveStatus", 0);
		// logger.info("cri:{}", cri);
		pager.setTotalSize(supplierApplyService.getListSize(cri).longValue());
		logger.info("totalSize:{}", pager.getTotalSize());
		objList = supplierApplyService.getList(pager.getCurrentPage() * pager.getPageRecord(), pager.getPageRecord(), cri,
				new String[] { "supplierID asc" });
		// logger.info("pager.getPageSize()():{}", pager.getPageSize());
		// logger.info("objList.size():{}", objList.size());
		jsonOut = new HashMap();
		jsonOut.put("total", pager.getPageSize());
		jsonOut.put("page", pager.getCurrentPage());
		jsonOut.put("records", pager.getTotalSize());
		jsonOut.put("objList", objList);
		return "jsonListOut";
	}

	public String supplierPops() {
		return "supplierPops";
	}

	public String memberAddressList() {
		logger.debug("param:{}", getParamMap());
		Map<String, String> drMap = deliveryRuleService.findDeliveryType("cart", getParamMap().get("cartId"));
		String deliveryType = drMap.get("deliveryType");
		if (StringUtils.equalsIgnoreCase(ServerValue.getScmType(), deliveryType)) {
			objList = memberService.getCanUseAddressBook(getParamMap().get("memberId"), deliveryType, drMap
					.get("fromProvince"), drMap.get("fromCity"), drMap.get("fromDistrict"));
		} else {
			// 大材积
			Map<String, String> prodVolumeMap = cartordersService.chkVolumeOfCartOrderDetail(getParamMap().get("cartId"));
			if (prodVolumeMap.size() > 0) {
				objList = memberService.getCanUseAddressBook(getParamMap().get("memberId"), deliveryType, "", "", "", true);
			} else {
				objList = memberService.getCanUseAddressBook(getParamMap().get("memberId"), deliveryType, "", "", "");
			}
		}
		pager.setTotalSize(objList.size());

		jsonOut = new HashMap();
		jsonOut.put("total", pager.getPageSize());
		jsonOut.put("page", pager.getCurrentPage());
		jsonOut.put("records", pager.getTotalSize());
		jsonOut.put("objList", objList);
		return "jsonListOut";
	}

	public String memberAddressPops() {
		return "memberAddressPops";
	}

	public String product() {
		if (StringUtils.isNotBlank(id)) {
			try {
				obj = productService.get(id);
			} catch (Exception e) {
				logger.error("get product fail", e);
			}
		}
		return "jsonOut";
	}

	public String productPops() {
		CommonCriteria cri = new CommonCriteria();
		Date now = DateUtil.getCurrentTime();
		// cri.addIn("level", Arrays.asList("0", "1"));
		cri.addIn("level", Arrays.asList("0"));
		cri.addLe("startDate", now);
		cri.addGe("endDate", now);
		cri.addEq("isVisible", "Y");
		objList = categoryService.getList(0, -1, cri, new String[] { "categoryPath asc" });
		return "productPops";
	}

	public String category() {
		if (StringUtils.isNotBlank(id)) {
			try {
				obj = categoryService.get(Long.valueOf(id));
			} catch (Exception e) {
				logger.error("get product fail", e);
			}
		}
		return "category";
	}

	public String categoryChild() {
		if (StringUtils.isNotBlank(id)) {
			try {
				List categories = categoryService.getAvailableChild(Long.valueOf(id));
				jsonOut = new HashMap();
				jsonOut.put("objList", categories);
			} catch (Exception e) {
				logger.error("get product fail", e);
			}
		}
		return "jsonListOut";
	}

	public String user() {
		if (StringUtils.isNotBlank(id)) {
			try {
				obj = userService.get(id);
			} catch (Exception e) {
				logger.error("get user fail", e);
			}
		}
		return "user";
	}

	public String shelf() {
		if (StringUtils.isNotBlank(id)) {
			try {
				obj = shelfService.getActiveShelfByProductId(id);
			} catch (Exception e) {
				logger.error("get shelf fail", e);
			}
		}
		return "shelf";
	}

	public String brandList() {
		logger.debug("param:{}", getParamMap());
		CommonCriteria cri = new CommonCriteria();
		cri.addEq("brandStatus", "Y");
		if (StringUtils.isNotBlank(getParamMap().get("brandId"))) {
			cri.addRlike("brandId", getParamMap().get("brandId"));
		}
		if (StringUtils.isNotBlank(getParamMap().get("brandName"))) {
			cri.addRlike("brandName", getParamMap().get("brandName"));
		}

		String[] sortOrder = { "brandId" };
		int entitySize = productService.getBrandList(0, -1, cri, sortOrder).size();
		pager.setTotalSize(entitySize);
		pager.setPageRecord(10);// defaut 20

		pager.setTotalSize(Long.parseLong(String.valueOf(productService.getBrandList(0, -1, cri, sortOrder).size())));
		objList = productService.getBrandList(pager.getCurrentPage() * pager.getPageRecord(), pager.getPageRecord(), cri,
				sortOrder);
		// objList = productService.getBrandList(0, -1, cri, sortOrder);
		logger.info("pager.getPageSize()():{}", pager.getPageSize());
		logger.info("objList.size():{}", objList.size());
		jsonOut = new HashMap();
		jsonOut.put("total", pager.getPageSize());
		jsonOut.put("page", pager.getCurrentPage());
		jsonOut.put("records", pager.getTotalSize());
		jsonOut.put("objList", objList);
		return "jsonListOut";
	}

	public String brandPops() {
		return "brandPops";
	}

	public String getCouponCode() {
		return couponCode;
	}

	public void setCouponCode(String couponCode) {
		this.couponCode = couponCode;
	}

	public List<Map<String, Object>> getCouponLogsList() {
		return couponLogsList;
	}

	public void setCouponLogsList(List<Map<String, Object>> couponLogsList) {
		this.couponLogsList = couponLogsList;
	}

	public String getCartId() {
		return cartId;
	}

	public void setCartId(String cartId) {
		this.cartId = cartId;
	}

}
